package sql

import (
	shadow "FlyFight/Internal/Shadow"
	. "FlyFight/typego"
	"log"

	"gorm.io/gorm"
)

func CreatePlayer(player *Player) error {
	result := db.Create(player)
	if result.Error != nil {
		log.Printf("创建玩家失败: %v", result.Error)
		return result.Error
	}
	log.Printf("玩家创建成功, UID: %d", player.Uid)
	return nil
}

// GetPlayerByUID 通过UID获取玩家
func GetPlayerByUID(uid int,player *Player) (error) {
	result := db.First(&player, "uid = ?", uid)
	
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			log.Printf("玩家不存在, UID: %d", uid)
			return nil
		}
		log.Printf("查询玩家失败: %v", result.Error)
		return result.Error
	}
	
	return  nil
}
//通过用户名称获取玩家
func GetPlayerByName(name string,player *Player) (error) {
	result := db.Where("usr_name = ?", name).First(&player)
	
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			log.Printf("玩家不存在, 名称: %s", name)
			return nil
		}
		log.Printf("查询玩家失败: %v", result.Error)
		return result.Error
	}
	return  nil
}


//获取所有玩家
func LoadAllPlayer() ([]Player, error) {
	var players []Player
	result := db.Find(&players)
	if result.Error != nil {
		log.Printf("查询所有玩家失败: %v", result.Error)
		return nil, result.Error
	}
	return players, nil
}

//根据uid设置加盐密码
func SetPass(uid int, pass string)	{
	str,err:=shadow.HashPassword(pass)
	if err!=nil{
		log.Printf("设置密码失败: %v", err)
		return 
	}
	var pshadow PassShadow
	pshadow.Pass=str
	pshadow.Uid=uid
	p:=db.Create(&pshadow)
	if p.Error!=nil{
		log.Printf("设置密码失败: %v", p.Error)
		return 
	}
	log.Printf("设置密码成功, UID: %d", uid)
}

func ChangePass(uid int, pass string) bool {
	var pshadow PassShadow
	p:=db.First(&pshadow,uid)
	if p.Error!=nil{
		log.Printf("查询密码失败: %v", p.Error)
		return false
	}
	p=db.Model(&pshadow).Update("Pass", pass)
	if p.Error!=nil{
		log.Printf("修改密码失败: %v", p.Error)
		return false
	}
	return true
}

func CheckPass(uid int, pass string) bool {
	var pshadow PassShadow
	p:=db.First(&pshadow,uid)
	if p.Error!=nil{
		log.Printf("查询密码失败: %v", p.Error)
		return false
	}
	if shadow.CheckPasswordHash(pass,pshadow.Pass){
		return true
	}
	return false
}